﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CCompilerUI {
    public partial class MainForm : Form {
        private bool changed;
        private string sourceFile = "";

        public MainForm() {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e) {
            CodeEdit.Document.SyntaxFile = Application.StartupPath + "\\c.syn";
            changed = false;
            UpdateFormTitle();
        }

        private void NewButton_Click(object sender, EventArgs e) {
            sourceFile = "";
            CodeEdit.Document.Text = "";
            changed = false;
            UpdateFormTitle();
        }

        private void OpenButton_Click(object sender, EventArgs e) {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = "(*.c) C files | *.c";
            if (openDlg.ShowDialog() != DialogResult.OK)
                return;

            sourceFile = openDlg.FileName;
            CodeEdit.Document.Text = File.ReadAllText(sourceFile);
            changed = false;
            UpdateFormTitle();
        }

        private void CompileButton_Click(object sender, EventArgs e) {
            if (SaveFile()) {
                CompileForm compWind = new CompileForm(sourceFile);
                compWind.Show();
            }
        }

        private void SaveButton_Click(object sender, EventArgs e) {
            SaveFile();
        }

        private void UpdateFormTitle() {
            string changed = this.changed ? "*" : "";
            Text = "C Compiler - " + (sourceFile == "" ? "Untitled" : new FileInfo(sourceFile).Name) + changed;
        }

        private bool SaveFile() {
            if (sourceFile == "") {
                SaveFileDialog saveDlg = new SaveFileDialog();
                saveDlg.Filter = "(*.c) C files | *.c";
                if (saveDlg.ShowDialog() != DialogResult.OK)
                    return false;

                sourceFile = saveDlg.FileName;
            }

            File.WriteAllText(sourceFile, CodeEdit.Document.Text);
            changed = false;
            UpdateFormTitle();

            return true;
        }

        private void CodeEdit_TextChanged(object sender, EventArgs e) {
            changed = true;
            UpdateFormTitle();
        }
    }
}
